/***************************************** 
 * Desc: Mask相关的控制，只控制一层子对象
 * @Author: GSan
 * @Email: 2087653648@qq.com
 * CreateDate: 2020-07-24 14:47:13
*****************************************/

using UnityEngine;
using UnityEngine.UI;

namespace Common.UGUI.Tool {

	[RequireComponent(typeof(Mask))]
	public class UGUIMaskControl : MonoBehaviour {

        #region 域

        private RectTransform _transform = null;
        private Vector2 _maskOriginPos = Vector3.zero;

        private RectTransform[] _children = null;
        private Vector2[] _childrenOriginPoses = null;

        #endregion

        #region Unity生命周期
        
        private void Awake() {

            _transform = (RectTransform)transform;
        }

        private void Start() {

            RefreshMaskOriginPosition();

            RefreshChildrenOriginPositions();
        }

        private void OnDestroy() {

            _transform = null;
        }

        #endregion

        #region 移动相关

        /// <summary>
        /// 刷新此时的Mask对象位置为标准位置
        /// </summary>
        public void RefreshMaskOriginPosition() {
            _maskOriginPos = _transform.anchoredPosition;
        }

        /// <summary>
        /// 刷新此时的Mask子对象缓存
        /// </summary>
        public void RefreshChildrenOriginPositions() {

            int childCount = _transform.childCount;

            _children = new RectTransform[childCount];
            _childrenOriginPoses = new Vector2[childCount];

            //统一所有被遮罩对象的对象方式
            for (int i = 0; i < childCount; ++i) {

                RectTransform rect = _transform.GetChild(i) as RectTransform;

                rect.anchorMin = new Vector2(0.5f, 0.5f);
                rect.anchorMax = new Vector2(0.5f, 0.5f);

                _children[i] = rect;
                _childrenOriginPoses[i] = rect.anchoredPosition;
            }
        }

        /// <summary>
        /// 设置此时Mask的位置且不影响所有子对象的相对位置
        /// </summary>
        public void SetMaskPosition(Vector2 newPosition) {

            Vector2 movedVector = newPosition - _maskOriginPos;

            for (int i = 0; i < _children.Length; ++i) {

                _children[i].anchoredPosition = _childrenOriginPoses[i] - movedVector;
            }

            _transform.anchoredPosition = newPosition;
        }

        #endregion
    }
}
